/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RRHH_controlador;

import Conexion.Conexion;
import RRHH_Modelo.RHH_DATOS;
import RRHH_Modelo.RHH_FECHAS_HITO;
import RRHH_Modelo.RHH_PERSONA;
import RRHH_Modelo.RHH_PERSONA_DATOS;
import RRHH_Modelo.RHH_USUARIO;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 *
 * @author equipo_4
 */
@MultipartConfig
@WebServlet(name = "RRHH_DOCUMENTOS_FALTANTES_CONTROLLER", urlPatterns = {"/RRHH_DOCUMENTOS_FALTANTES_CONTROLLER"})
public class RRHH_DOCUMENTOS_FALTANTES_CONTROLLER extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RRHH_DOCUMENTOS_FALTANTES_CONTROLLER</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RRHH_DOCUMENTOS_FALTANTES_CONTROLLER at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            RHH_USUARIO usuario = ((RHH_USUARIO)request.getSession().getAttribute("usr"));
            Conexion con = new Conexion(usuario.getPASSWORD(), usuario.getPASSWORD());    
            
            String evento = request.getParameter("proceso");
            String html="";
            switch(evento)
            {
                                 
                case "actualizar":
                    html=actualizar(request,con);                    
                    break;   
                case "buscarEmpleado":
                    html=buscarEmpleado(request,con);
                    break;
                case "cargardatos":
                    html=cargardatos(request,con);
                    break;
            }
            
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            response.getWriter().write(html);
            con.Close();
        } catch (Exception ex) {
            
        } 
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    private String cargardatos(HttpServletRequest request, Conexion con) throws SQLException {
        int id=Integer.parseInt(request.getParameter("idpersona"));
        int idcargo=Integer.parseInt(request.getParameter("cargo"));
        RHH_PERSONA_DATOS pd=new RHH_PERSONA_DATOS(con);
        List<Integer> listadato=pd.BuscarDatosFaltantes(id,idcargo);
        String html="";
        for (int i = 0; i < listadato.size(); i++) {
            RHH_DATOS dato=new RHH_DATOS(con).BuscarXid(listadato.get(i));
            String caducidad="";
            if(dato.getESTADO_CADUCIDAD()==1){
                    caducidad="Caducidad Documento <input type='text' class='chico fecha' style=' margin-left: 7px;' name='"+dato.getID()+"_o'/><br>";
            }
            if(dato.getTIPO()==1){
               html+="<div style='border-bottom: 2px solid silver;' data-iddato='"+dato.getID()+"'>"
                    + "<span class='negrillaenter'  style='font-size: 16px; text-align: center;'>"+dato.getDESCRIPCION()
                    +"</span>"+caducidad
                    +"<span >Nombre Archivo:</span><br><span></span><input type='file' onchange=\"openFile(event,this,2);\" name='"+dato.getID()+"' value='' style='display:none;'/><img src='../img/Upload-files.jpg' "
                    + "onclick=\"abrirFile("+dato.getID()+")\" alt='' "
                    + "style='width: 25px; margin: 0px 10px; border-radius: 4px;'/><img src='../img/ver.jpg' "
                    + "alt='' onclick='abrirdocumento(this)' name='verdocs'  style='width: 28px; height:28px;  margin: 0px -5px; border-radius: 10px;'/>"+"<br></div>";
           }else{
               html+="<div data-class='dato' style='border-bottom: 2px solid silver;' data-iddato='"+dato.getID()+"'>"
                           + "<span class='negrillaenter' style='font-size: 16px; text-align: center;'>"+dato.getDESCRIPCION()+"</span>"
                           + "<input type='text' name='"+dato.getID()+"' value=''/><br></div>";
           }
            
        }
        return html;
    }
    private String buscarEmpleado(HttpServletRequest request, Conexion con) throws SQLException {
        String text=request.getParameter("text");
        RHH_PERSONA persona=new RHH_PERSONA(con);
        RHH_USUARIO usuario=new RHH_USUARIO(con);
        List<RHH_USUARIO> lista=usuario.personasSinDocumentos(text);
        String html="";
        RHH_FECHAS_HITO hito=new RHH_FECHAS_HITO(con);
        for (int i = 0; i < lista.size(); i++) {
            persona=persona.BuscarxID(lista.get(i).getID_PERSONA());
            String src="../img/imagen3.jpg";
            String nombre=persona.getPRIMER_NOMBRE()+" ";
            if(persona.getSEGUNDO_NOMBRE()!=null || !persona.getSEGUNDO_NOMBRE().equals("null")){
                nombre+=persona.getSEGUNDO_NOMBRE()+" ";
            }
            nombre+=persona.getPRIMER_APELLIDO();
            if(persona.getSEGUNDO_APELLIDO()!=null || !persona.getSEGUNDO_APELLIDO().equals("null")){
                nombre+=" "+persona.getSEGUNDO_APELLIDO()+" ";
            }
           
            double sueldo=hito.salarioUsuario(lista.get(i).getID());
            html+="<div data-salario='"+sueldo+"' onclick=\"abrirPop('"+persona.getID()+"','"+lista.get(i).getID_CARGO()+"',0)\" style=\"padding: 5px; width: 106px; background: none repeat scroll 0% 0% white; border-radius: 7px; height: 135px; margin: 5px; float:left;\">\n" +
                        "<div class=\"centrado negrilla\" class='ci'>"+persona.getCI()+"</div>\n" +
                        "<div style=\"height: 80px; width: 104px;\">\n" +
                            "<img style=\"width: 100%; height: 100%;\" class='imagen' data-ci='" + persona.getCI()+ "' data-foto='"+persona.getFOTO()+"' alt=\"\" src=\""+src+"\">\n" +
                        "</div>\n" +
                        "<div class=\"centrado\">"+nombre+"</div>\n" +
"                   </div>";
        }
        return html;
    }
   

    private String actualizar(HttpServletRequest request, Conexion con) throws IOException, ServletException, SQLException, ParseException, IllegalStateException, FTPIllegalReplyException, FTPException, FTPAbortedException, FTPDataTransferException {
        int idus=Integer.parseInt(request.getParameter("idus"));
        RHH_PERSONA per = new RHH_PERSONA(con).BuscarxID(idus);
        SimpleDateFormat formato1 = new SimpleDateFormat("dd/MM/yyyy");
        List<RHH_DATOS> dtlist = new RHH_DATOS(con).TodosDatos();

        for (int i = 0; i < dtlist.size(); i++) {
            RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(con);
            String dato = request.getParameter(dtlist.get(i).getID() + "");
            String fecha = request.getParameter(dtlist.get(i).getID()+"_o");
            if (dato != null) {
                if (dato.length() > 0) {
                    pd.setID_DATOS(dtlist.get(i).getID());
                    pd.setID_PERSONA(idus);
                    pd.setDATO(dato);
                    if (fecha != null && fecha.length() != 0) {
                        pd.setCADUCIDAD(formato1.parse(fecha));
                    }
                    pd.Insertar();
                }
            }
        }
        List<RHH_DATOS> doclist = new RHH_DATOS(con).TodosDocs();
        for (int i = 0; i < doclist.size(); i++) {
            RHH_PERSONA_DATOS pd = new RHH_PERSONA_DATOS(con);
            Part pdoc = request.getPart(doclist.get(i).getID() + "");
            if (pdoc != null) {
                String nom = pdoc.getSubmittedFileName();
                if (nom.length() > 0) {
                    pd.setID_DATOS(doclist.get(i).getID());
                    pd.setID_PERSONA(idus);
                    pd.setDATO(pdoc.getSubmittedFileName());
                    pd.Insertar();
                    InputStream in = pdoc.getInputStream();
                    subirftp(in,per.getCI()+"" ,pdoc.getSubmittedFileName(), pdoc.getSize(),"");
                }
            }
        }      
        return true+"";        
    }
    
    private void subirftp(Part part, String ci, String nombre,String old) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException
    {
        FTPClient client = new FTPClient();          
        client.connect("192.168.0.101");
        client.login("postulado","oracle123");
        InputStream in = part.getInputStream();
        long size = part.getSize();
        try{
            client.createDirectory(ci);
            client.changeDirectory(ci);
        }
        catch(Exception e)
        {
            client.changeDirectory(ci);
        }
        try{
            client.deleteFile(old);
        }catch(Exception e){}                
        client.upload(nombre, in, size, 0, null);        
        client.disconnect(false);
        in.close();
    }
     private void subirftp(InputStream in, String ci, String nombre, long size, String old) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException {
        if (in != null && !nombre.equals("")) {
            FTPClient client = new FTPClient();
            client.connect("192.168.0.101");
            client.login("postulado", "oracle123");

            try {
                client.createDirectory(ci);
                client.changeDirectory(ci);
            } catch (Exception e) {
                client.changeDirectory(ci);
            }
            try {
                client.deleteFile(old);
            } catch (Exception e) {
            }
            client.upload(nombre, in, size, 0, null);

            client.disconnect(false);
        }
    }
}
